package com.pakaroid.android.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.Toast;

import com.pakaroid.android.app.utils.Consts;

public class SettingActivity extends ListActivity {

    private static final String TAG = "SettingActivity";

    private ArrayList<String> mPackageNames;
    private ArrayList<Integer> mPackageNamePositions;
    
	private int mIconSize = 72;
//	private PakaroidApplication mPakaroidApplication;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_main);
        
        setResult(RESULT_CANCELED);
        
        mIconSize = getResources().getDimensionPixelSize(R.dimen.icon_size);

		mPackageNames = new ArrayList<String>();
		mPackageNamePositions = new ArrayList<Integer>();
        
        (findViewById(R.id.okBtn)).setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
//		        int max = mPackageNames.size();
		        int max = mPackageNamePositions.size();
		        
		        SharedPreferences.Editor prefs = getSharedPreferences(Consts.PREFS_NAME, MODE_PRIVATE).edit();
		        
		        for(int i = 0; i < Consts.MAX_APP_NUM; i++) {
		        	if(i < max) {
//		        		String name = mPackageNames.get(i);
//		        		prefs.putString(Consts.PREF_PREFIX_KEY + i, name);
//		        		Log.d(TAG, Consts.PREF_PREFIX_KEY + i + " : " + name);
		        		int position = mPackageNamePositions.get(i);
		        		prefs.putInt(Consts.PREF_PREFIX_KEY_INT + i, position);
		        		Log.d(TAG, Consts.PREF_PREFIX_KEY_INT + i + " : " + position);
	        	}
		        	else {
//		        		prefs.putString(Consts.PREF_PREFIX_KEY + i, null);		        		
		        		prefs.putInt(Consts.PREF_PREFIX_KEY_INT + i, -1);
		        	}
		        }		        
		        prefs.commit();
				
		        setResult(RESULT_OK, null);
				finish();
			}
		});
        
        LoadAppTask task = new LoadAppTask();
        task.execute();
	}
	
	public class LoadAppTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
	        loadApplications(true);
	        return null;
		}
	 
	    @Override
	    protected void onPostExecute(Void param) {
	        bindApplications();
	    	(findViewById(R.id.progress)).setVisibility(View.GONE);
	    }
	}	

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		CheckedTextView ctv = (CheckedTextView)v;
//		ApplicationInfo info = (ApplicationInfo)l.getAdapter().getItem(position);
//		String packageName = (String)info.pakcageName;
		
//		if(!ctv.isChecked()){
//			if(!mPackageNames.contains(packageName)) {
//				mPackageNames.add(packageName);
//			}
//		}
//		else {
//			if(mPackageNames.contains(packageName)) {
//				mPackageNames.remove(packageName);
//			}
//		}
		if(!ctv.isChecked()){
			if(!mPackageNamePositions.contains(position)) {
				mPackageNamePositions.add(position);
			}
		}
		else {
			if(mPackageNamePositions.contains(position)) {
				mPackageNamePositions.remove(new Integer(position));
			}
		}
	}

    /**
     * Loads the list of installed applications in mApplications.
     */
    private void loadApplications(boolean isLaunching) {
//   		mPackageNames = new ArrayList<String>();
   		mPackageNamePositions = new ArrayList<Integer>();
    	    	
        SharedPreferences prefs = getSharedPreferences(Consts.PREFS_NAME, MODE_PRIVATE);
        for(int i = 0; i < Consts.MAX_APP_NUM; i++){
//        	String packageName = prefs.getString(Consts.PREF_PREFIX_KEY + i, null);
//        	if(packageName != null) {
//        		mPackageNames.add(packageName);
//        		Log.d(TAG, "loadApplications (read from SD): " + i + ", " + packageName);
//        	}

        	int position = prefs.getInt(Consts.PREF_PREFIX_KEY_INT + i, -1);
        	if(position != -1) {
        		mPackageNamePositions.add(position);
        		Log.d(TAG, "loadApplications (read from SD): " + i + ", " + position);
        	}
        }    	

        if (isLaunching && PakaroidApplication.mApplications != null) {
//        	ArrayList<ApplicationInfo> mApplications = PakaroidApplication.mApplications;
//        	
//        	for(int i = 0; i < mApplications.size(); i++) {
//        		ApplicationInfo application = mApplications.get(i);
////                if(mPackageNames.contains(application.pakcageName)){
////                	mDefaultCheckedPosition.add(i);
////            		Log.d(TAG, "loadApplications (match with apps): " + i + ", " + application.pakcageName);                	
////                }
//                if(mPackageNamePositions.contains(i)){
//                	mDefaultCheckedPosition.add(i);
//            		Log.d(TAG, "loadApplications (match with apps): " + i + ", " + application.pakcageName);                	
//                }
//            }
        }
        else {
            PackageManager manager = getPackageManager();

            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

            final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
            Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));

            if (apps != null) {
                final int count = apps.size();

            	ArrayList<ApplicationInfo> mApplications = new ArrayList<ApplicationInfo>(count);

                for (int i = 0; i < count; i++) {
                    ApplicationInfo application = new ApplicationInfo();
                    ResolveInfo info = apps.get(i);

                    application.title = info.loadLabel(manager);
                    application.pakcageName = info.activityInfo.packageName;
                    application.icon = info.activityInfo.loadIcon(manager);
            		application.setActivity(new ComponentName(
                            info.activityInfo.applicationInfo.packageName,
                            info.activityInfo.name),
                            Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

//                    if(mPackageNames.contains(application.pakcageName)){
////                    	mDefaultCheckedPosition.add(i);
//                		Log.d(TAG, "loadApplications (match with apps): " + i + ", " + application.pakcageName);                	
//                    }
                    mApplications.add(application);
                }
                
                PakaroidApplication.mApplications = mApplications;
            }
        }
    }
    
    /**
     * Creates a new applications adapter for the grid view and registers it.
     */
    private void bindApplications() {
    	setListAdapter(new ApplicationsAdapter(this, PakaroidApplication.mApplications));
    	
    	ListView lv = getListView();
    	
    	lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    	lv.setSelection(0);
    	
    	for(int i : mPackageNamePositions) {
    		lv.setItemChecked(i, true);
    	}
    }
    
    /**
     * GridView adapter to show the list of all installed applications.
     */
    private class ApplicationsAdapter extends ArrayAdapter<ApplicationInfo> {
        private Rect mOldBounds = new Rect();

        public ApplicationsAdapter(Context context, ArrayList<ApplicationInfo> apps) {
            super(context, 0, apps);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ApplicationInfo info = PakaroidApplication.mApplications.get(position);

            if (convertView == null) {
                final LayoutInflater inflater = getLayoutInflater();
                convertView = inflater.inflate(android.R.layout.simple_list_item_multiple_choice, parent, false);
                
                convertView.setOnTouchListener(new View.OnTouchListener() {
        			
        			@Override
        			public boolean onTouch(View v, MotionEvent event) {
        				boolean isChecked = ((CheckedTextView)v).isChecked();
        				
        				if(isChecked) {
        					return false;					
        				}
        				
        				long[] checkedItemIds = getListView().getCheckItemIds();
        				if(checkedItemIds.length >= Consts.MAX_APP_NUM) {
        					Toast.makeText(SettingActivity.this, R.string.cannot_check, Toast.LENGTH_SHORT).show();
        					return true;
        				}
        				return false;
        			}
        		});
            }

            Drawable icon = info.icon;

            if (!info.filtered) {
                int width = mIconSize;
                int height = mIconSize;

                final int iconWidth = icon.getIntrinsicWidth();
                final int iconHeight = icon.getIntrinsicHeight();

                if (icon instanceof PaintDrawable) {
                    PaintDrawable painter = (PaintDrawable) icon;
                    painter.setIntrinsicWidth(width);
                    painter.setIntrinsicHeight(height);
                }

                if (width > 0 && height > 0 && (width != iconWidth || height != iconHeight)) {
//                if (width > 0 && height > 0 && (width < iconWidth || height < iconHeight)) {
                    final float ratio = (float) iconWidth / iconHeight;

                    if (iconWidth > iconHeight) {
                        height = (int) (width / ratio);
                    } else if (iconHeight > iconWidth) {
                        width = (int) (height * ratio);
                    }

                    final Bitmap.Config c =
                            icon.getOpacity() == PixelFormat.OPAQUE ?
                            		Bitmap.Config.RGB_565 : Bitmap.Config.ARGB_8888;
                    final Bitmap thumb = Bitmap.createBitmap(width, height, c);
                    final Canvas canvas = new Canvas(thumb);
                    canvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, 0));

                    mOldBounds.set(icon.getBounds());
                    icon.setBounds(0, 0, width, height);
                    icon.draw(canvas);
                    icon.setBounds(mOldBounds);
                    icon = info.icon = new BitmapDrawable(thumb);
                    info.filtered = true;
                }
            }
            
            final CheckedTextView textView = ((CheckedTextView) convertView);
            textView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
            textView.setCompoundDrawablePadding(20);
            textView.setText(info.title);

            return convertView;
        }
    }

}
